//
//  NetWorkTools.swift
//  NetWorkTools
//
//  Created by 裘明 on 15/9/3.
//  Copyright © 2015年 qm. All rights reserved.
//


import UIKit
import AFNetworking
import ReactiveCocoa

/// 网络请求方法
enum requestMethod: String {
    
    case GET = "GET"
    case POST = "POST"
}

/// 网络工具类
class NetWorkTools: AFHTTPSessionManager {
    
    //  MARK: - App信息
    /// 申请应用时分配的AppKey
    private let clientId = "4028897073"
    /// 申请应用时分配的AppSecret
    private let appSecret = "5a91cb69b6c1972018ae0b22213f4604"
    /// 回调地址，需与注册应用里的回调地址一致
    let redirectUri = "http://www.baidu.com"
    
    //  单例
    static let shareNetwork: NetWorkTools = {
        
        // 指定baseURL
        var instance = NetWorkTools(baseURL: nil)
        // 设置反序列化的支持格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    //  MARK: - 微博数据
    
    ///   加载当前登录用户微博数据(需要token)
    /// - params  since_id  若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    /// - - params max_id  若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    /// - returns: RAC Signal
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(since_id since_id: Int, max_id: Int) -> RACSignal {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 创建空的参数字典
        var params = [String: AnyObject]()
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        return request(.GET, URLString: urlString, parameters: params)
    }
    
    
    
    //  MARK: - OAuth，获取请求码
    
    ///        拼接字符串,向网页客户端发送请求，获取Code
    /// OAuth  授权地址，返回请求码
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    
    ///   获取AccessToken，获取口令
    ///   将code发送给服务器，获取口令
    /// - parameter code: 请求码/授权码
    ///
    /// - see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func loadAccessToken(code:String) -> RACSignal {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        /// 请求参数
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        return request(.POST, URLString: urlString, parameters: params, WithToken: false)
    }
    
    ///   加载用户信息
    ///
    /// - parameter uid: 需要查询的用户ID
    ///
    /// - returns:       RAC Signal
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUseInfo(uid: String) -> RACSignal {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid]
        
        return request(.GET, URLString: urlString, parameters: params)
    }
    
    /// 网络请求方法（对AFN的get\post请求方法进行封装）
    ///
    /// - parameter Method:     请求方法
    /// - parameter URLString:  urlString
    /// - parameter parameters: 需要的参数
    /// - parameter WithToken:  是否需要口令，默认是要
    ///
    /// - returns:              RAC signal
    private func request(Method:requestMethod, URLString:String, var parameters:[String: AnyObject]?, WithToken:Bool = true) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            // 0.判断是否需要Token
            if WithToken {
                // 如果Token不存在，发送请求错误
                guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
                    
                    subscriber.sendError(NSError(domain: "mq.weibo.com", code: -120, userInfo: ["errorMessage": "token为空"]))
                    
                    return nil
                }
                // 判断是否传递了参数
                if parameters == nil {
                    
                    parameters = [String: AnyObject]()
                }
                parameters!["access_token"] = token

            }
            // 1.成功时的回调
            let successCallBack = { (task:NSURLSessionDataTask, result:AnyObject) -> Void in
                
                subscriber.sendNext(result)
                subscriber.sendCompleted()
            }
            // 2.失败时的回调
            let failureCallBack = { (task:NSURLSessionDataTask, error:NSError) -> Void in
                
                subscriber.sendError(error)
                
            }
            
            if Method == requestMethod.GET {
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            } else {
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }
            
            return nil
        })
        
    }

}










